package com.utils;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;

import java.io.*;
import java.util.Iterator;
import java.util.Set;

public class CookiesUtils {
    private static CookiesUtils cookiesUtils = null;

    private static synchronized void init() {
        cookiesUtils = new CookiesUtils();
    }

    public static CookiesUtils getCookiesUtils() {
        if (cookiesUtils == null) {
            init();
        }
        return cookiesUtils;
    }

    //保存cookes
    public void saveCookies(Set<Cookie> set, String cookiesPath) throws IOException {
        FileOutputStream outputStream = new FileOutputStream(cookiesPath);
        ObjectOutputStream oos = new ObjectOutputStream(outputStream);
        oos.writeObject(set);
        outputStream.close();
        oos.close();
    }

    public void readCookies(String cookiesPath, WebDriver webDriver) throws IOException, ClassNotFoundException {
        FileInputStream inputStream = new FileInputStream(cookiesPath);
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        Set<Cookie> set = (Set<Cookie>) objectInputStream.readObject();
        inputStream.close();
        objectInputStream.close();
        Iterator<Cookie> its = set.iterator();
        WebDriver.Options options = webDriver.manage();
        try {
            while (its.hasNext()) {
                options.addCookie(its.next());
            }
        } catch (Exception ex) {
            LogCustom logCustom = new LogCustom(this.getClass().getSuperclass());
            logCustom.error(ex.getMessage());
        }
    }

}
